package org.example.chat_room.component;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class OnlineUserManager {
    private ConcurrentHashMap<Integer, WebSocketSession> sessions = new ConcurrentHashMap<>();

//  用户上线
    public void online(int userId,WebSocketSession session){
        if (sessions.get(userId) != null){
//            用户已经在线了，登录失败
            System.out.println("["+userId+"]"+"已经上线，登录失败！");
            return;
        }
        sessions.put(userId,session);
        System.out.println("["+userId+"]"+"上线！！");
    }

//    用户下线
    public void offline(int userId,WebSocketSession session){
        WebSocketSession existsSession = sessions.get(userId);
        if (existsSession == session){
            sessions.remove(userId);
            System.out.println("["+userId+"]"+"下线！");
        }
    }

    public WebSocketSession getSession(int userId){
        return sessions.get(userId);
    }

}
